<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/12
 * Time: 10:54
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;


use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use think\facade\Log;

/**
 * cdiscount 接口服务 composer require autumndev/cdiscount-sdkphpapi
 * Class CdiscountService
 * @package app\common\service\cdiscount
 * @link https://dev.cdiscount.com/marketplace/?page_id=128
 */
class CdiscountService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'access_key',
                'field' => 'access_key',
            ],
            [
                'type' => 'text',
                'name' => 'secret_key',
                'field' => 'secret_key',
            ],
        ],
        'option' => [ // 可选字段
        ],
    ];

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 开始抓取时间，默认为今天</li>
     * <li>string end_date 结束抓取时间，默认为当前时间</li>
     * <li>string[] status 要抓取的订单状态，默认["Shipped", "WaitingForShipmentAcceptation", "AcceptedBySeller"]</li>
     * <li>string channel 要抓取的订单类型，默认MFN</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @return array|bool
     * @date 2020/02/20
     * @author longli
     */
    public function getOrderList($params = [], $replace = false)
    {
        $startSyncTime = time();
        Log::info(sprintf("cdiscout 批量同步账号【%d】订单，请求参数:【%s】", $this->getAccountId(), json_encode($params)));
        $startDate = !empty($params['start_date'])
            ? $this->formatTimeToDate($params['start_date'])
            : $this->formatTimeToDate(date('Y-m-d'));
        $endDate = !empty($params['end_date'])
                   ? $this->formatTimeToDate($params['end_date'])
                   : $this->formatTimeToDate();
        $token = $this->getAccessToken();
        $orderStatus = ["Shipped", "WaitingForShipmentAcceptation", "AcceptedBySeller"];
        if(!empty($params['status']) && is_array($params['status'])) $orderStatus = $params['status'];
        $status = [];
        foreach($orderStatus as $s)
        {
            $status[] = ["OrderStateEnum" => $s];
        }
        $xml = Tools::arrayToXml([
            "s:Body" => [
                "GetOrderList" => [
                    "headerMessage" => [
                        "a:Context" => [
                           "a:CatalogID" => 1,
                           "a:CustomerPoolID"  => 1,
                           "a:SiteID" => 100,
                        ],
                        "a:Localization" => [
                            "a:Country" => "Fr",
                            "a:Currency" => "Eur",
                            "a:DecimalPosition" => 2,
                            "a:Language" => "Fr"
                        ],
                        "a:Security" => [
                            "a:DomainRightsList" => [],
                            "attr@a:DomainRightsList" => ["i:nil" => "true"],

                            "a:IssuerID" => [],
                            "attr@a:IssuerID" => ["i:nil" => "true"],

                            "a:SessionID" => [],
                            "attr@a:SessionID" => ["i:nil" => "true"],

                            "a:SubjectLocality" => [],
                            "attr@a:SubjectLocality" => ["i:nil" => "true"],
                            "a:TokenId" => $token,

                            "a:UserName" => [],
                            "attr@a:UserName" => ["i:nil" => "true"],
                        ],
                        "a:Version" => "1.0"
                    ],
                    "attr@headerMessage" => [
                        "xmlns:a" => "http://schemas.datacontract.org/2004/07/Cdiscount.Framework.Core.Communication.Messages",
                        "xmlns:i" => "http://www.w3.org/2001/XMLSchema-instance"
                    ],
                    "orderFilter" => [
                        "BeginCreationDate" => $startDate,
                        "BeginModificationDate" => $startDate,
                        "EndCreationDate" => $endDate,
                        "EndModificationDate" => $endDate,
                        "FetchOrderLines" => "true",
                        "States" => $status,
                    ],
                    "attr@orderFilter" => ["xmlns:i" => "http://www.w3.org/2001/XMLSchema-instance"]
                ],
                "attr@GetOrderList" => [
                    "xmlns" => "http://www.cdiscount.com"
                ]
            ],
        ], ["name" => "s:Envelope", "attribute" => ["xmlns:s" => "http://schemas.xmlsoap.org/soap/envelope/"]]);

        $header = [
            "Content-Type: text/xml",
            "SoapAction: http://www.cdiscount.com/IMarketplaceAPIService/GetOrderList"
        ];
        $response = Tools::curlPost($this->getBaseUrl() . "/MarketplaceAPIService.svc", $xml, $header);
        if(!$response['status'])
        {
            Log::info("cdiscount 同步订单出错, 账号：【" . $this->getAccountId() . "】");
            return false;
        }
        // 解析订单
        $data = Tools::xmlToArray($response['data'], "s:Body");
        if(!empty($data[0]["GetOrderListResponse"]["GetOrderListResult"]["OrderList"]))
        {
            foreach($data[0]["GetOrderListResponse"]["GetOrderListResult"]["OrderList"] as $order)
            {
                $this->pushOrderToTemp($order['OrderNumber'], $order, $replace);
            }
        }
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $params);
    }

    /**
     * 获取请求 token, 成功返回 token 失败返回 false
     * @date 2020/08/12
     * @author longli
     * @return bool|string
     */
    public function getAccessToken()
    {
        Log::info(sprintf("cdiscount 获取账号【%d】token", $this->getAccountId()));
        $account = $this->getAccount();
        $keyUrl = "https://sts.cdiscount.com/users/httpIssue.svc/?realm=https://wsvc.cdiscount.com/MarketplaceAPIService.svc";
        $header = [
            "Content-Type:application/json;",
            "Accept:application/json",
            "Authorization: Basic " . base64_encode($account->token->access_key . ":" . $account->token->secret_key),
        ];
        $response = Tools::curlGet($keyUrl, [], $header);
        if(!$response['status']) return false;
        return xmlrpc_decode($response['data']);
    }

    /**
     * @inheritDoc
     */
    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $info = [];
        $oneSku = false;
        foreach($data['OrderLineList']['OrderLine'] as $detail)
        {
            if(!is_array($detail))
            {
                $oneSku = true;
                $detail = $data['OrderLineList']['OrderLine'];
            }
            $info[] = [
                "platform_sku"      => $detail['Sku'], // sku
                "name"              => is_array($detail['Name']) ? join(', ', $detail['Name']) : $detail['Name'], // 产品在平台的名称
                "qty"               => $detail['Quantity'], // 数量
                "price"             => $detail['PurchasePrice'], // 产品价格
            ];
            if($oneSku) break;
        }
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data['OrderState'], // 订单在平台的状态
            "buyer_first_name"          => $data['ShippingAddress']['FirstName'], // 客户名称
            "buyer_last_name"           => $data['ShippingAddress']['LastName'], // 客户名称
            "buyer_mobile"              => $data['Customer']['MobilePhone'], // 手机
            "buyer_country_code"        => $data['ShippingAddress']['Country'], // 国家编码
            "buyer_company"             => is_array($data['ShippingAddress']['CompanyName']) ? join(', ', $data['ShippingAddress']['CompanyName']) : $data['ShippingAddress']['CompanyName'], // 公司
            "buyer_district"            => $data['ShippingAddress']['Street'], // 街道
            "buyer_city"                => $data['ShippingAddress']['City'], // 城市
            "buyer_post_code"           => $data['ShippingAddress']['ZipCode'], // 邮编
            "buyer_address_1"           => (is_array($data['ShippingAddress']['Instructions']) ? join(', ', $data['ShippingAddress']['Instructions']) : $data['ShippingAddress']['Instructions']) . $data['ShippingAddress']['Street'], // 买家收货地址
            "order_source_create_time"  => $this->parseTimeToDate($data['CreationDate']), // 订单在平台生成的时间
            "latest_delivery_time"      => $this->parseTimeToDate(!empty($data["OrderLineList"]["OrderLine"]["ShippingDateMax"])? $data["OrderLineList"]["OrderLine"]["ShippingDateMax"] : $data["OrderLineList"]["OrderLine"][0]["ShippingDateMax"]), // 最迟发货时间
            "order_price"               => $data['InitialTotalAmount'],
            "total_price"               => $data['InitialTotalAmount'] + $data['InitialTotalShippingChargesAmount'], // 订单总金额
            "commission_cost"           => $data['SiteCommissionValidatedAmount'], // 平台佣金
            "currency"                  => 'EUR',
            'order_detail'              => $info,
        ];
        return OrderService::getInstance()->addOrder($order);
    }

    public function markDelivery($orderIds = [])
    {
        // @todo 标记平台发货
    }
}